<?php
/**
-------------------------
GNU GPL COPYRIGHT NOTICES
-------------------------
This file is part of FlexicaCMS.

FlexicaCMS is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

FlexicaCMS is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with FlexicaCMS.  If not, see <http://www.gnu.org/licenses/>.*/

/**
 * $Id$
 *
 * @author FlexicaCMS team <contact@flexicacms.com>
 * @link http://www.flexicacms.com/
 * @copyright Copyright &copy; 2009-2010 Gia Han Online Solutions Ltd.
 * @license http://www.flexicacms.com/license.html
 */

class ModulesController extends BackOfficeController
{
//    public $layout = 'modules';

    public function actionIndex(){
        $this->render('List');
    }

    public function actionDashboard(){
        Yii::app()->layout = 'module';
        $this->render('Dashboard');
    }

    public function actionAll()
    {
        //detect modules
        $this->detectModules();

        $model = new Module('search');
        if(isset($_GET['Module']))
            $model->attributes=$_GET['Module'];

        if ($model->Enabled == 0) $model->Enabled = null;
        if ($model->IsSystem == 0) $model->IsSystem = null;
        $this->render('AllModules', array('model' => $model));
    }

    /**
    * detect modules
    *
    */
    protected function detectModules() {
        $modulePath = Yii::app()->getModulePath();
        $modules=array();
        $handle=opendir($modulePath);
        while(($file=readdir($handle))!==false)
        {
            if($file==='.' || $file==='..' || $file === '.svn')
                continue;
            $path=$modulePath.DIRECTORY_SEPARATOR.$file;
            if (is_dir($path)) {
                $modules[]=basename($path);
            }
        }
        closedir($handle);

        $configChanged = false;
        if (count($modules)) {
            $enabled = Yii::app()->getModules();
            foreach($modules as $name) {
                if (! Module::model()->count('Name=:name', array(':name'=>$name))) {
                    $module = new Module();
                    $module->Name = $name;
                    $module->Title = ucfirst($name);
                    $module->Enabled = array_key_exists($name, $enabled) ? Module::ENABLED_YES : Module::ENABLED_NO;
                    if ($module->save()) {
                        $configChanged = true;
                    } else {
                        Yii::log('Load Modules error: '.CVarDumper::dumpAsString($module->getErrors()), CLogger::LEVEL_ERROR, 'application.Cms.controllers.admin.ModulesController');
                    }
                }
            }
        }
        //create config file
        if (Yii::app()->hasComponent('config') && (Yii::app()->getComponent('config')->hasConfigFile('modules') === false || $configChanged)) {
            $this->initConfigCache();
        }
    }

    protected function initConfigCache() {
        $modules = array();
        $activeModules = Module::model()->findAll('Enabled='.Module::ENABLED_YES);
        if (count($activeModules) > 0) {
            foreach ($activeModules as $module) {
                $modules[] = $module->Name;
            }
        }
        $id = 'modules';
        Yii::app()->getComponent('config')->saveConfig($id, array('modules'=>$modules));
    }

    public function actionEdit()
    {
        $moduleId = $this->get('Id', 0);
        if ($moduleId == 0)
            $module = new Module();
        else
            $module = Module::model()->findByAttributes(array('Id'=>$moduleId));

        $this->render('Edit', array('module' => $module));
    }

    public function actionSave()
    {
        //Make sure this action can be requested only by POST
        if ($this->IsPostBack)
        {
            // Check create a new article of edit an existing article
            $url = $this->createUrl('/BackOffice/admin/modules/edit', array('Id' => $this->post('Module[Id]')));

            $result = Cms::service('BackOffice/Module/update', $_POST);
            if ($result->ReturnCode == ServiceResult::RETURN_SUCCESS)
            {
                //create config file
                $this->initConfigCache();
                $moduleId = $this->post('Module[Id]', 0);
                if ($moduleId == 0)
                    $this->message = Yii::t('Module', 'MODULE_CREATE_SUCCESSFUL');
                else
                    $this->message = Yii::t('Module', 'MODULE_UPDATE_SUCCESSFUL');
            }

            // log error
            if ($result->ReturnCode != ServiceResult::RETURN_SUCCESS){
                ErrorHandler::logErrors($result->ErrorMessages);
            }

            // redirect
            $this->redirect($url);
        }
        else
        {
            $this->redirect($this->createUrl('/BackOffice/admin/modules/all'));
        }
    }

    public function actionEnabled() {
        if(Yii::app()->request->isPostRequest)
        {
            if (isset($_GET['id'])) {
                $model = Module::model()->find('Id = :id', array(':id'=>$this->get('id')));
                $model->changeEnabled();
                $this->initConfigCache();
            }

            if(!isset($_GET['ajax']))
                $this->redirect(array('index'));
        }
        else
            throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
    }

    public function actionRebuildCache() {
        if (Yii::app()->hasComponent('config') && (Yii::app()->getComponent('config')->hasConfigFile('modules') === true)) {
            Yii::app()->getComponent('config')->removeConfigFile('modules');
        }
        $this->redirect($this->createUrl('all'));
    }
}